import pathToRegexp from 'path-to-regexp';
import { queryDoctorLevelList } from '../services/register';

export default {
  namespace: 'doctorLevelList',
  state: {
    doctorLevels: [],
  },
  reducers: {
    fetchDoctorLevelListSuccess(state, { payload }) {
      return {
        ...state,
        doctorLevels: payload,
      };
    },
  },
  effects: {
    *fetchDoctorLevelList({
      payload,
    }, { put, call }) {
      const { data } = yield call(queryDoctorLevelList, payload);
      const list = data.data.map((d) => {
        return {
          name: d.levelName,
          code: d.levelCode,
        };
      });
      yield put({
        type: 'fetchDoctorLevelListSuccess',
        payload: list,
      });
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen((location) => {
        const match = pathToRegexp('/selectDoctorLevel').exec(location.pathname);
        if (match) {
          dispatch({
            type: 'fetchDoctorLevelList',
            payload: {
            },
          });
        }
      });
    },
  },
};
